// * @author Kamlesh Singh, Copyright (C) 2006, All Rights Reserved
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace HTTP_TUNNEL
{
	/// <summary>
	/// Summary description for httptunnel.
	/// </summary>
	public class httptunnel
	{
		public httptunnel()
		{
			//
			// TODO: Add constructor logic here
			//
		}

		private IPHostEntry proxyentry ;
		private IPAddress  proxyip ;
		private IPEndPoint proxyendpoint;
		public static Socket mysocket;
		
		public Socket createHttpTunnel(string proxyipadd,string port,string struid,string strpwd,string destip,string destport)
		{
			proxyentry = Dns.Resolve(proxyipadd);
			proxyip = proxyentry.AddressList[0];
			int iPORT = Int32.Parse(port);
			proxyendpoint = new IPEndPoint(proxyip,iPORT);
			 mysocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
			mysocket.Connect(proxyendpoint);
			string EncodedData = encodeUIDPWD(struid.ToString(),strpwd.ToString());

			string proxymsgmsg = "CONNECT " + destip +":" + destport +" HTTP/1.0\nProxy-Authorization:Basic " + EncodedData +  "\n\n" ;
			byte[] buffer = Encoding.ASCII.GetBytes(proxymsgmsg);
			byte[] buffer12 = new byte[500];
			mysocket.Send(buffer,buffer.Length,0);
			int msg = mysocket.Receive(buffer12,500,0);
			string data;
			data = Encoding.ASCII.GetString(buffer12);
			int index = data.IndexOf("200");
			
			if(index == -1)
			{
			//	return 0;
			}
			else 
			{
				//return 1;
				return mysocket;
			}
		}
		public string encodeUIDPWD(string uid, string pwd)
		{
			string uidpwd = uid + ":" + pwd;
			byte[] data = System.Text.UnicodeEncoding.UTF8.GetBytes(uidpwd);
			Base64Encoder myEncoder = new Base64Encoder(data);
			StringBuilder sb = new StringBuilder();
			sb.Append(myEncoder.GetEncoded());
			return (sb.ToString());

		}
	}
}
